package com.niodata.dp.app;

import com.niodata.dp.app.dao.AppInfoMapper;
import com.niodata.dp.app.dao.VariableMapper;
import com.niodata.dp.core.exception.InvalidStatusException;
import com.niodata.dp.task.dao.TaskMapper;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("appManagerImpl")
public class DefaultAppManager implements AppManager {

  @Autowired
  private AppInfoMapper appInfoMapper;

  @Autowired
  private VariableMapper variableMapper;

  @Autowired
  private TaskMapper taskMapper;

  @Override
  public List<AppInfo> getUserAuthorizedApps(long userId, String keyWord, int offset, int count) {

    return appInfoMapper.findUserAuthorizedApps(userId, offset, count, keyWord);
  }

  @Override
  public List<AppInfo> getUserApps(long userId, String keyWord) {
    return appInfoMapper.findUserApps(userId, keyWord);
  }

  @Override
  @Transactional
  public void createApp(AppInfo appInfo) {
    appInfoMapper.save(appInfo);
  }

  @Override
  @Transactional
  public void deleteApp(String appId) throws IOException {
    if (taskMapper.existsTaskInApp(appId)) {
      throw new InvalidStatusException("应用中还有未删除的流程,删除失败!");
    }
    if (variableMapper.existsVariablesInApp(appId)) {
      throw new InvalidStatusException("应用中还有未删除的变量，删除失败!");
    }
    appInfoMapper.delete(appId);
  }

  @Override
  public void updateApp(AppInfo appInfo) {
    appInfoMapper.update(appInfo);
  }

  @Override
  public AppInfo getByAppId(String appId) {
    return appInfoMapper.getByAppId(appId);
  }

  @Override
  public AppInfo getByAppCode(String appCode) {
    return appInfoMapper.getByCode(appCode);
  }
}
